package com.dayu.web.controller.store;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dayu.common.core.redis.RedisCache;
import com.dayu.common.utils.SecurityUtils;
import com.dayu.recovery.domain.RecoveryCollect;
import com.dayu.recovery.service.IRecoveryCollectService;
import com.dayu.store.domain.StoreData;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import com.dayu.common.annotation.Log;
import com.dayu.common.core.controller.BaseController;
import com.dayu.common.core.domain.AjaxResult;
import com.dayu.common.enums.BusinessType;
import com.dayu.store.domain.StoreCollect;
import com.dayu.store.service.IStoreCollectService;
import com.dayu.common.utils.poi.ExcelUtil;
import com.dayu.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 门店回收Controller
 * 
 * @author HK
 * @date 2021-07-02
 */
@RestController
@RequestMapping("/store/collect")
public class StoreCollectController extends BaseController
{
    @Autowired
    private IStoreCollectService storeCollectService;
    @Autowired
    private IRecoveryCollectService collectService;

    @Resource
    private RedisCache redisCache;

    /**
     * 查询门店回收列表
     */
    @PreAuthorize("@ss.hasPermi('store:collect:list')")
    @GetMapping("/list")
    public TableDataInfo list(StoreCollect storeCollect)
    {
        startPage();
        List<StoreCollect> list = storeCollectService.selectStoreCollectList(storeCollect);
        return getDataTable(list);
    }

    /**
     * 根据ids查询列表
     * @param storeIds
     * @return
     */
    @PreAuthorize("@ss.hasPermi('store:collect:list')")
    @GetMapping("/list/{storeIds}")
    public AjaxResult listByIds(@PathVariable Long[] storeIds) {
        List<StoreCollect> list = storeCollectService.selectStoreCollectByIds(storeIds);
        return AjaxResult.success(list);
    }

    @PreAuthorize("@ss.hasPermi('store:collect:price')")
    @GetMapping("/price/total")
    public AjaxResult listPriceTotal(StoreCollect storeCollect) {
        List<StoreCollect> list = storeCollectService.selectStoreCollectList(storeCollect);
        Map<String, Object> respMap = new HashMap<>();
        BigDecimal price = new BigDecimal(0);
        BigDecimal priceOne = new BigDecimal(0);
        BigDecimal priceTwo = new BigDecimal(0);
        BigDecimal priceThree = new BigDecimal(0);
        BigDecimal expPrice = new BigDecimal(0);
        for(StoreCollect collect: list) {
            if(collect.getPrice() != null) {
                price = price.add(collect.getPrice());
            }
            if(collect.getPriceOne() != null) {
                priceOne = priceOne.add(collect.getPriceOne());
            }
            if(collect.getPriceTwo() != null) {
                priceTwo = priceTwo.add(collect.getPriceTwo());
            }
            if(collect.getPriceThree() != null) {
                priceThree = priceThree.add(collect.getPriceThree());
            }
            if(collect.getExpPrice() != null) {
                expPrice = expPrice.add(collect.getExpPrice());
            }
        }
        BigDecimal total = price.add(priceOne).add(priceTwo).add(priceThree).add(expPrice);
        respMap.put("price", price);
        respMap.put("priceOne", priceOne);
        respMap.put("priceTwo", priceTwo);
        respMap.put("priceThree", priceThree);
        respMap.put("expPrice", expPrice);
        respMap.put("total", total);
        return AjaxResult.success(respMap);
    }

    /**
     * 导出门店回收列表
     */
    @PreAuthorize("@ss.hasPermi('store:collect:export')")
    @Log(title = "门店回收", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(StoreCollect storeCollect)
    {
        List<StoreCollect> list = storeCollectService.selectStoreCollectList(storeCollect);
        for (StoreCollect collect:
             list) {
            collect.setTotalPrice(new BigDecimal(0));
            collect.setExportCompany();
        }
        ExcelUtil<StoreCollect> util = new ExcelUtil<StoreCollect>(StoreCollect.class);
        return util.exportExcel(list, "collect");
    }

    @PreAuthorize("@ss.hasPermi('store:collect:export')")
    @Log(title = "门店回收统计", businessType = BusinessType.EXPORT)
    @GetMapping("/export/data")
    public AjaxResult exportData(StoreCollect storeCollect) {
        List<StoreData> list = storeCollectService.selectStoreDataList(storeCollect);
        ExcelUtil<StoreData> util = new ExcelUtil<>(StoreData.class);
        return util.exportExcel(list, "门店回收统计");
    }

    /**
     * 获取门店回收详细信息
     */
    @PreAuthorize("@ss.hasPermi('store:collect:query')")
    @GetMapping(value = "/{storeId}")
    public AjaxResult getInfo(@PathVariable("storeId") Long storeId)
    {
        return AjaxResult.success(storeCollectService.selectStoreCollectById(storeId));
    }


    @GetMapping(value = "/avgUseTime")
    public AjaxResult avgUseTime()
    {
        return AjaxResult.success(storeCollectService.queryAvgUseTimeList());
    }

    /**
     * 新增门店回收
     */
    @PreAuthorize("@ss.hasPermi('store:collect:add')")
    @Log(title = "门店回收", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StoreCollect storeCollect)
    {
        return toAjax(storeCollectService.insertStoreCollect(storeCollect));
    }

    @PreAuthorize("@ss.hasPermi('store:collect:add')")
    @Log(title = "门店回收", businessType = BusinessType.INSERT)
    @PostMapping("/adds")
    public AjaxResult addList(@RequestBody List<StoreCollect> list) {
        return toAjax(storeCollectService.insertList(list));
    }

    /**
     * 修改门店回收
     */
    @PreAuthorize("@ss.hasPermi('store:collect:edit')")
    @Log(title = "门店回收", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StoreCollect storeCollect)
    {
        return toAjax(storeCollectService.updateStoreCollect(storeCollect));
    }

    /**
     * 删除门店回收
     */
    @PreAuthorize("@ss.hasPermi('store:collect:remove')")
    @Log(title = "门店回收", businessType = BusinessType.DELETE)
	@DeleteMapping("/{storeIds}")
    public AjaxResult remove(@PathVariable Long[] storeIds)
    {
        return toAjax(storeCollectService.deleteStoreCollectByIds(storeIds));
    }

    /**
     * 批量新增
     * @param map
     * @return
     */
    @PreAuthorize("@ss.hasPermi('store:collect:add')")
    @PostMapping("/add/list")
    public AjaxResult addList(@RequestBody String map) {
        JSONObject reqMap = JSON.parseObject(map);
        Integer number = reqMap.getInteger("number");
        return toAjax(storeCollectService.insertStoreCollectList(number));
    }

    /**
     * 数据使用按钮事件
     * @param storeId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('store:collect:use')")
    @Log(title = "门店回收使用", businessType = BusinessType.UPDATE)
    @GetMapping("/use/{storeId}")
    public AjaxResult useCollect(@PathVariable Long storeId) {
        StoreCollect selCollect = storeCollectService.selectStoreCollectById(storeId);
        if(selCollect == null) {
            return AjaxResult.error("没有获取到数据！");
        }
        if(selCollect.getStatus() != 1) {
            return AjaxResult.error("此数据状态为不可用！");
        }
        selCollect.setStatus(2); //待发货
        selCollect.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        selCollect.setCreateTime(new Date());
        return toAjax(storeCollectService.updateStoreCollect(selCollect));
    }

    @PreAuthorize("@ss.hasPermi('store:collect:take')")
    @Log(title = "门店回收收货事件", businessType = BusinessType.DELETE)
    @GetMapping("/take/{storeId}")
    public AjaxResult takeOver(@PathVariable Long storeId) {
        StoreCollect selCollect = storeCollectService.selectStoreCollectById(storeId);
        if(selCollect == null) {
            return AjaxResult.error("没有获取到数据！");
        }
        if(!(selCollect.getStatus() == 3 || selCollect.getStatus() == 2)) {
            return AjaxResult.error("此数据状态不可收货！");
        }
        selCollect.setStatus(4); //已收货
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        selCollect.setCollectInfo(SecurityUtils.getLoginUser().getUser().getNickName() +"(收货)_"+ dateFormat.format(new Date()));
        selCollect.setCollectTime(new Date());
        return toAjax(storeCollectService.updateStoreCollect(selCollect));
    }

    /**
     * 关闭
     * @param storeId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('store:collect:close')")
    @GetMapping("/close/{storeId}")
    public AjaxResult close(@PathVariable Long storeId) {
        StoreCollect selCollect = storeCollectService.selectStoreCollectById(storeId);
        if(selCollect == null) {
            return AjaxResult.error("没有获取到数据！");
        }
        selCollect.setStatus(5); //关闭
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String info = SecurityUtils.getLoginUser().getUser().getNickName() +"(关闭)_"+ dateFormat.format(new Date());
        if(selCollect.getCollectInfo() != null) {
            selCollect.setCollectInfo(selCollect.getCollectInfo() + " > " + info);
        }else {
            selCollect.setCollectInfo(info);
        }
        return toAjax(storeCollectService.updateStoreCollect(selCollect));
    }

    /**
     * 审核
     * @param storeId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('store:collect:audit')")
    @Log(title = "门店回收审核事件", businessType = BusinessType.UPDATE)
    @GetMapping("/audit/{storeId}")
    public AjaxResult audit(@PathVariable Long storeId) {
        StoreCollect selCollect = storeCollectService.selectStoreCollectById(storeId);
        if(selCollect == null) {
            return AjaxResult.error("没有获取到数据！");
        }
        /*if(selCollect.getStatus() != 4) {
            return AjaxResult.error("数据状态不对！");
        }*/
        if(selCollect.getBillStatus() != 1) {
            return AjaxResult.error("数据已审核!");
        }
        selCollect.setBillStatus(2); //已审核
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        selCollect.setCheckInfo(SecurityUtils.getLoginUser().getUser().getNickName() +"_"+ dateFormat.format(new Date()));
        return toAjax(storeCollectService.updateStoreCollect(selCollect));
    }

    @PreAuthorize("@ss.hasPermi('store:collect:audit')")
    @Log(title = "门店回收审核事件", businessType = BusinessType.UPDATE)
    @GetMapping("/audit/list/{ids}")
    public AjaxResult auditList(@PathVariable Long[] ids) {
        return toAjax(storeCollectService.auditList(ids));
    }

    /**
     * 报价师 报价数据总数统计
     * @param storeCollect
     * @return
     */
    @PreAuthorize("@ss.hasPermi('store:collect:list')")
    @GetMapping("/offer/data/list")
    public AjaxResult offerDataList(StoreCollect storeCollect) {
        List<Map<String, Object>> respList = storeCollectService.offerDataList(storeCollect);
        return AjaxResult.success(respList);
    }

    /**
     * 门店回收数据 批量收货
     * @param recoveryCollect
     * @return
     */
    @PreAuthorize("@ss.hasPermi('store:collect:take')")
    @Log(title = "门店回收收货事件", businessType = BusinessType.DELETE)
    @PostMapping("/take/list")
    public AjaxResult addAndUpdateCollect(@RequestBody RecoveryCollect recoveryCollect) {
        storeCollectService.updateStoreCollectByList(recoveryCollect.getStoreIdsInLong());
        return toAjax(collectService.insertRecoveryCollect(recoveryCollect));
    }

    @PreAuthorize("@ss.hasPermi('store:collect:haspay')")
    @Log(title = "门店回收打款事件", businessType = BusinessType.UPDATE)
    @GetMapping("/has/pay/{storeId}")
    public AjaxResult updateHasPay(@PathVariable Long storeId) {
        return toAjax(storeCollectService.updateHayPay(storeId));
    }

    /**
     * 修改热门机型
     */
    @PreAuthorize("@ss.hasPermi('edit:hot:mobile')")
    @PostMapping("/editHotMobile")
    public AjaxResult editHotMobile(@RequestBody Map<String, Object> name) {
        String key = "hot_mobile_key";
        redisCache.setCacheObject(key, name);
        return AjaxResult.success();
    }

    @GetMapping("/queryHotMobile")
    public AjaxResult queryHotMobile() {
        String key = "hot_mobile_key";
        Map<String, Object> name = redisCache.getCacheObject(key);
        return AjaxResult.success(name);
    }

    /**
     * 回收价格分布
     */
    @GetMapping("/chatDataPrice")
    public AjaxResult chatDataPrice() {
        return AjaxResult.success(storeCollectService.queryPriceChatData());
    }
}
